package SingleMachineArrangeImpl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//最大延迟问题（有准备时间，不可中断，工件加工时间均为1）
public class EDDrp1 extends SingleMachineArrange{

    //判断所有工件是否处于就绪状态
    private boolean[] isReady(int t,int[] ready,int[] process){
        boolean[] result = new boolean[ready.length];
        //计算最早的交付时间
        for (int i=0;i<ready.length;i++){
            if(ready[i] <= t && process[i] >0) result[i] = true;
        }
        return result;
    }

    private boolean isComplete(int[] process){
        for (int p : process) {
            if(p>0) return false;
        }
        return true;
    }

    //从就绪工件中选择交付期限最小的加工
    private int chooseArtifact(boolean[] is_ready,int[] process, int[] ready, int[] due){
        int art = -1;
        int min_due = Integer.MAX_VALUE;
        for (int i = 0; i < is_ready.length; i++) {
            if(!is_ready[i]) continue;
            if(due[i] < min_due){
                min_due = due[i];
                art = i;
            }
        }
        return art;
    }

    @Override
    public void solve() {
        if(ready==null||due==null){
            ready = new int[]{0, 1, 1, 2, 3, 5};
            due = new int[]{1, 2, 3, 2, 4, 5};
        }
        //process可能是其他数值
        if(process==null) {
            process = new int[ready.length];
            Arrays.fill(process, 1);
        }
        List<Integer> seq = new ArrayList<>();
        int art = -1;
        for (int t=0;!isComplete(process);){
            boolean[] ready1 = isReady(t, ready, process);
            art = chooseArtifact(ready1,process,ready,due);
            //当前没有可加工工件，跳出循环
            if(art==-1) {t++;continue;}
            //加工被选中的工件
            t += process[art];
            process[art] = 0;
            seq.add(art+1);
        }
        System.out.println("加工顺序：" + seq);
    }
}
